import React from 'react';
import { Card, Button, Table, Space, Modal, message, TableProps } from 'antd';
import { useParams } from 'react-router-dom';
import _ from 'lodash';
import { FormPanelObject, InputType } from 'lfun-bg-comp';
import { YES_NO } from '@/constant/basicOptions';
import utils from '@/utils';
import FormPanelWrapper from '../../component/FormPanelWrapper';
import { TeaLearnExperienceSrv } from '@/service/teacher';
import {
  EDUCATION_LEVEL,
  EDUCATION_NAME,
  HIGHEST_EDUCATION,
  INSTITUTION_TYPE,
  LEARNING_METHOD,
  MAJOR,
} from '@/constant/teachOptions';
import { countries } from '@/constant/country';
import { isPermissionOperate } from '@/component/permission-button';

export const list = [
  {
    title: '',
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    span: 12,
    inputs: [
      {
        label: '获得学历',
        name: 'education_obtained',
        key: 'education_obtained',
        required: true,
        inputType: InputType.cascader,
        renderOption: HIGHEST_EDUCATION,
      },
      {
        label: '获得学历国家(地区)',
        name: 'country_or_region_of_education',
        key: 'country_or_region_of_education',
        required: true,
        inputType: InputType.select,
        renderOption: countries,
      },
      {
        label: '获得学历院校/机构',
        name: 'institution_of_education_obtained',
        key: 'institution_of_education_obtained',
        required: true,
        textRange: [0, 20],
      },
      {
        label: '所学专业',
        name: 'major_learned',
        key: 'major_learned',
        required: true,
        inputType: InputType.cascader,
        renderOption: MAJOR,
      },
      {
        label: '是否师范类专业',
        name: 'is_major_normal',
        key: 'is_major_normal',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      {
        label: '入学年月',
        name: 'admission_date',
        key: 'admission_date',
        inputType: InputType.date,
      },
      {
        label: '毕业年月',
        name: 'graduation_date',
        key: 'graduation_date',
        inputType: InputType.date,
      },
      {
        label: '学位层次',
        name: 'degree_level',
        key: 'degree_level',
        required: true,
        inputType: InputType.select,
        renderOption: EDUCATION_LEVEL,
      },
      {
        label: '学位名称',
        name: 'degree_name',
        key: 'degree_name',
        required: true,
        inputType: InputType.cascader,
        renderOption: EDUCATION_NAME,
      },
      {
        label: '获得学位国家(地区)',
        name: 'country_or_region_of_degree_obtained',
        key: 'country_or_region_of_degree_obtained',
        required: true,
        inputType: InputType.select,
        renderOption: countries,
      },
      {
        label: '获得学位院校/机构',
        name: 'institution_of_degree_obtained',
        key: 'institution_of_degree_obtained',
        required: true,
        textRange: [0, 20],
      },
      {
        label: '学位授予年月',
        name: 'degree_award_date',
        key: 'degree_award_date',
        required: true,
        inputType: InputType.date,
      },
      {
        label: '学习方式',
        name: 'study_mode',
        key: 'study_mode',
        required: true,
        inputType: InputType.select,
        renderOption: LEARNING_METHOD,
      },
      {
        label: '在学单位类别',
        name: 'type_of_institution',
        key: 'type_of_institution',
        inputType: InputType.cascader,
        renderOption: INSTITUTION_TYPE,
      },
    ],
  },
];
const LearnExp: React.FC<{ isEditPanel?: boolean }> = ({ isEditPanel = true }) => {
  const { id: teacher_id } = useParams();
  const columns: TableProps['columns'] = [
    {
      title: '获得学历',
      dataIndex: 'education_obtained',
      key: 'education_obtained',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(HIGHEST_EDUCATION, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '获得学历国家（地区）',
      dataIndex: 'country_or_region_of_education',
      key: 'country_or_region_of_education',
      render: (text: any) => {
        return _.find(countries, { value: String(text) })?.label;
      },
    },
    {
      title: '获得学历院校机构',
      dataIndex: 'institution_of_education_obtained',
      key: 'institution_of_education_obtained',
    },
    {
      title: '所学专业',
      dataIndex: 'major_learned',
      key: 'major_learned',
    },
    {
      title: '是否师范类专业',
      dataIndex: 'is_major_normal',
      key: 'is_major_normal',
      render: (text: any) => {
        return _.find(YES_NO, { value: String(text) })?.label;
      },
    },
    {
      title: '入学年月',
      dataIndex: 'admission_date',
      key: 'admission_date',
    },
    {
      title: '毕业年月',
      dataIndex: 'graduation_date',
      key: 'graduation_date',
    },
    {
      title: '学位层次',
      dataIndex: 'degree_level',
      key: 'degree_level',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(EDUCATION_LEVEL, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '获得学位国家（地区）',
      dataIndex: 'country_or_region_of_degree_obtained',
      key: 'country_or_region_of_degree_obtained',
      render: (text: any) => {
        return _.find(countries, { value: String(text) })?.label;
      },
    },
    {
      title: '获得学位院校/机构',
      dataIndex: 'institution_of_degree_obtained',
      key: 'institution_of_degree_obtained',
    },
    {
      title: '学位授予年月',
      dataIndex: 'degree_award_date',
      key: 'degree_award_date',
    },
    {
      title: '学习方式',
      dataIndex: 'study_mode',
      key: 'study_mode',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(LEARNING_METHOD, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '在学单位类别',
      dataIndex: 'type_of_institution',
      key: 'type_of_institution',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(INSTITUTION_TYPE, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '操作',
      key: 'actions',
      //width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          {isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          )}
          {isEditPanel && (
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          )}
          {!isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              查看
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const [formValue, setFormValue] = React.useState({});
  const [dataSource, setDataSource] = React.useState([]);
  const [currentRowId, setCurrentRowId] = React.useState(null);

  React.useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const res = await TeaLearnExperienceSrv.list({ teacher_id });
    console.log('🚀 ~ fetchData ~ res:', res);
    if (res.success) {
      setDataSource(res.data);
    }
  };

  // 新增 | 编辑
  const [showFormModel, setFormModel] = React.useState(false);
  const [isEdit, setIsEdit] = React.useState(false);

  const handleAdd = () => {
    setIsEdit(false);
    setFormValue({});
    setFormModel(true);
  };

  const handleEdit = async (record: any) => {
    console.log('handleEdit ~ record:', record);
    setCurrentRowId(record.teacher_learn_experience_id);
    const { data } = await TeaLearnExperienceSrv.detail(record.teacher_learn_experience_id);
    const params = {
      ...data,
      degree_name: data.degree_name ? data.degree_name?.split(',') : [],
      degree_level: data.degree_level ? data.degree_level?.split(',') : [],
      education_obtained: data.education_obtained ? data.education_obtained?.split(',') : [],
      study_mode: data.study_mode ? data.study_mode?.split(',') : [],
      type_of_institution: data.type_of_institution ? data.type_of_institution?.split(',') : [],
    };
    console.log('handleEdit ~ params:', params);

    setIsEdit(true);
    setFormValue(params);
    setFormModel(true);
  };

  const handleDelete = (record: any) => {
    // content 按最字段内容为准，格式是否删除${证件类型}:${证件号码},姓名${姓名}的教师信息?
    const text = record.education_obtained.split(',');
    const arr: any[] = text.map(v => utils.findLabelDeep(HIGHEST_EDUCATION, String(v)));
    Modal.confirm({
      title: '删除',
      content: `是否删除获得学历: ${arr.join('-')} 相关信息?`,
      onOk: async () => {
        console.log('OK');
        const res = await TeaLearnExperienceSrv.delete(record.teacher_learn_experience_id);
        if (res.success) {
          message.success('删除成功');
          fetchData();
        }
      },
    });
  };

  const handleSave = async (formPanelObject: FormPanelObject) => {
    const values = formPanelObject.getFieldsValue();
    const params = {
      ...values,
      teacher_id,
    };

    params.admission_date = utils.formatTime(values.admission_date);
    params.degree_award_date = utils.formatTime(values.degree_award_date);
    params.graduation_date = utils.formatTime(values.graduation_date);
    params.degree_name = params.degree_name?.join(',');
    //params.degree_level = params.degree_level?.join(',');
    params.education_obtained = params.education_obtained?.join(',');
    //params.study_mode = params.study_mode?.join(',');
    params.type_of_institution = params.type_of_institution?.join(',');

    if (isEdit) {
      params.teacher_learn_experience_id = currentRowId;
    }
    console.log('🚀 ~ handleSave ~ params:', params);

    // 新增 | 编辑
    const server = isEdit ? 'update' : 'add';
    const res = await TeaLearnExperienceSrv[server](params);
    if (res.success) {
      message.success('保存成功');
      formPanelObject.resetFields();
      setFormModel(false);
      fetchData();
      setCurrentRowId(null);
    } else {
      formPanelObject.reVaildation(res);
    }
  };

  return (
    <Card title="学习经历" bordered={false}>
      {/* <Button type="primary" style={{ marginBottom: '20px' }} onClick={() => setShowNewModel(true)}> */}
      {isEditPanel && (
        <Button type="primary" style={{ marginBottom: '20px' }} onClick={handleAdd}>
          新增
        </Button>
      )}
      <Table dataSource={dataSource} columns={columns} scroll={{ x: 'max-content' }} />
      <FormPanelWrapper
        title={isEdit ? (isEditPanel ? '学习经历编辑' : '学习经历详情') : '学习经历新增'}
        visible={showFormModel}
        formValue={formValue}
        changeValue={setFormValue}
        formList={list}
        onCancel={() => setFormModel(false)}
        onSave={handleSave}
        isEdit={isEditPanel}
      />
    </Card>
  );
};

LearnExp.defaultProps = {
  isEditPanel: true,
};

export default LearnExp;
